(function ($) {

	var $galleryClose = $('div.gallery-close');
	var $galleryLeft = $('div.gallery-left');
	var $galleryRight = $('div.gallery-right');
	var $galleryPanel = $('div.gallery-panel');
	var $galleryBody = $('div.gallery-body');

	function hideArrow (index, len) {
		if (index === 0) {
			$galleryLeft.hide();
		}
		else if (index === len - 1) {
			$galleryRight.hide();
		}
		else {
			$galleryLeft.show();
			$galleryRight.show();
		}
	}

	$.fn.gallery = function (itemName) {
		var $this = $(this);
		var items = $this.find(itemName);
		var len = items.length;

		var current = 0;

		$('.show-thumb').click(function (e) {
			e.preventDefault();
		
			var $this = $(this).parent().find(itemName);
			var clickSrc = $this.attr('src');	
			$('img.gallery-show').attr('src', clickSrc);
			$galleryPanel.fadeIn();
			$galleryBody.fadeIn();
			$('body').addClass('gallery-open');

			var clickIndex = $this.attr('data-index');
			var clickid = $this.attr('data-id');
			$('.gallery-download').attr('data-id',clickid)
			hideArrow(clickIndex, len);
		});

		$galleryClose.click(function () {
			$galleryPanel.fadeOut();
			$galleryBody.fadeOut();
			$('body').removeClass('gallery-open');
			$galleryLeft.show();
			$galleryRight.show();
		});

		$galleryLeft.click(function () {
			var $prev = items.eq(--current);
			var prevSrc = $prev.attr('src');
			$('img.gallery-show').attr('src', prevSrc);
			hideArrow(current, len);
		});

		$galleryRight.click(function () {
			var $next = items.eq(++current);
			var nextSrc = $next.attr('src');
			$('img.gallery-show').attr('src', nextSrc);
			hideArrow(current, len);
		});
	};
})(jQuery);